package com.hnevc.broadcastdemo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private MyBroadCastReceiver myReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void buttonClick(View view) {
        int id = view.getId();
        Log.e(TAG,"buttonClick:"+id);
        switch (id){
            case R.id.id_btn_register:
            {//TODO 注册
                //定义过滤器
                IntentFilter filter = new IntentFilter();
                filter.addAction("zmm");
                //定义接受者对象
                myReceiver = new MyBroadCastReceiver();
                //注册
                registerReceiver(myReceiver,filter);
                break;
            }
            case R.id.id_btn_send:
            {
                //TODO 发送广播
                    //广播定义意图
                Intent intent = new Intent();
                intent.setAction("zmm");
                    //发送广播意图
                sendBroadcast(intent);
                break;
            }
            case R.id.id_btn_unregister:
            {
                //取消广播注册
                unregisterReceiver(myReceiver);
                break;
            }
        }
    }
    //定义广播接受者类
    class MyBroadCastReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.e(TAG,"onReceive:");
        }
    }
}
